package com.bnyy.medicalHousekeeper.moudle.message.fragment;

import android.Manifest;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.SizeUtils;
import com.bnyy.gbp.permission.PermissionHelper;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.base.BaseFragmentImpl;
import com.bnyy.medicalHousekeeper.moudle.message.activity.UserHomePageActivity;
import com.bnyy.medicalHousekeeper.moudle.message.adapter.ChatContactAdapter;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.bnyy.message.bean.ContactUser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.function.Consumer;

import butterknife.BindView;

/**
 * Author : 关炳鹏
 * Description :
 * Date : 2023/1/9
 **/
public class ChatContactsFragment extends BaseFragmentImpl {
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.iv_no_data)
    ImageView ivNoData;
    @BindView(R.id.tv_no_data)
    TextView tvNoData;
    @BindView(R.id.ll_no_data)
    LinearLayout llNoData;

    private ChatContactAdapter adapter;

    public static ChatContactsFragment getInstance(int type) {
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        ChatContactsFragment fragment = new ChatContactsFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.layout_recycler_view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        int type = getArguments().getInt("type", -1);

        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        HashMap<String, Object> params = new HashMap<>();
        params.put("type", type);
        params.put("address_book_list", new ArrayList<>());
        if (type == 2) {
            boolean b = PermissionHelper.checkPermission(Manifest.permission.READ_CONTACTS);
            if (b) {
                tvNoData.setText("通讯录好友暂未使用百年医养");
                getChatContacts(type, params);
            } else {
                tvNoData.setText("同步通讯录，看看哪些朋友在使用百年医养，然后加为好友");

                int dp12 = SizeUtils.dp2px(12);

                TextView tvGetContacts = new TextView(mContext);
                GradientDrawable bg = new GradientDrawable();
                bg.setCornerRadius(360);
                bg.setColor(ContextCompat.getColor(mContext, R.color.green_theme));
                tvGetContacts.setBackground(bg);

                tvGetContacts.setGravity(Gravity.CENTER);
                tvGetContacts.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
                tvGetContacts.setPadding(dp12 * 2, dp12, dp12 * 2, dp12);
                tvGetContacts.setTextColor(Color.WHITE);
                tvGetContacts.setText("查看通讯录好友");
                tvGetContacts.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PermissionHelper.getInstance().requestPermission(new PermissionHelper.RequestPermission() {
                            @Override
                            public String[] permissions() {
                                return new String[]{Manifest.permission.READ_CONTACTS};
                            }

                            @Override
                            public void granted(HashSet<String> granted) {
                                Cursor cursor = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
                                ArrayList<String> contacts = new ArrayList<>();
                                if (cursor != null) {
                                    while (cursor.moveToNext()) {
                                        int columnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                                        String phone = cursor.getString(columnIndex).replace(" ", "");
                                        if (!TextUtils.isEmpty(phone)) {
                                            contacts.add(phone);
                                        }
                                    }
                                    cursor.close();
                                }
                                if (contacts.size() > 0) {
                                    params.put("address_book_list", contacts);
                                }
                                getChatContacts(type, params);
                            }

                            @Override
                            public void denied(HashSet<String> denied) {
                                getChatContacts(type, params);
                            }
                        });
                    }
                });

                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(dp12, dp12, dp12, dp12);
                llNoData.addView(tvGetContacts, layoutParams);
                llNoData.setVisibility(View.VISIBLE);
            }
        } else {
            getChatContacts(type, params);
        }
    }

    private void getChatContacts(int type, HashMap<String, Object> params) {
        requestManager.request(requestManager.mMessageRetrofitService.getChatContacts(RequestManager.getJsonRequestBody(params)),
                new BaseObserverImpl<ArrayList<ContactUser>>() {
                    @Override
                    public void onSuccess(ArrayList<ContactUser> contactUsers) {
                        super.onSuccess(contactUsers);
                        if (contactUsers.size() > 0) {
                            llNoData.setVisibility(View.GONE);
                        } else {
                            llNoData.setVisibility(View.VISIBLE);
                        }
                        adapter = new ChatContactAdapter(mContext, type, new Consumer<ContactUser>() {
                            @Override
                            public void accept(ContactUser chatContact) {
                                UserHomePageActivity.show(mContext, chatContact.getId(), chatContact.getRole_id());
                            }
                        }, new ChatContactAdapter.Callback() {
                            @Override
                            public void remove(int position) {
                                HashMap<String, Object> params = new HashMap<>();
                                params.put("id", adapter.getData(position).getId());
                                params.put("type", type);
                                requestManager.request(requestManager.mMessageRetrofitService.removeChatContacts(RequestManager.getJsonRequestBody(params)),
                                        new BaseObserverImpl<Object>(mContext) {
                                            @Override
                                            public void onSuccess() {
                                                super.onSuccess();
                                                adapter.remove(position);
                                                if (adapter.getDatas().size() == 0) {
                                                    llNoData.setVisibility(View.VISIBLE);
                                                }
                                            }
                                        });
                            }

                            @Override
                            public void focusOrNot(int position) {
                                ContactUser contactUser = adapter.getData(position);
                                HashMap<String, Object> params = new HashMap<>();
                                params.put("id", contactUser.getId());
                                params.put("act", contactUser.getStatus() == 2 ? 1 : 2);
                                requestManager.request(requestManager.mMessageRetrofitService.focusOrNot(RequestManager.getJsonRequestBody(params)),
                                        new BaseObserverImpl<Object>(mContext) {
                                            @Override
                                            public void onSuccess() {
                                                super.onSuccess();
                                                contactUser.setStatus(contactUser.getStatus() == 1 ? 2 : 1);
                                                adapter.notifyItemChanged(position);
                                            }
                                        });
                            }
                        });

                        recyclerView.setAdapter(adapter);
                        adapter.refresh(contactUsers);
                    }
                });
    }
}









































